Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) — Push element x onto stack.
  • pop() — Removes the element on top of the stack.
  • top() — Get the top element.
  • getMin() — Retrieve the minimum element in the stack.

Example:

  1. MinStack minStack = new MinStack();
  2. minStack.push(-2);
  3. minStack.push(0);
  4. minStack.push(-3);
  5. minStack.getMin(); --> Returns -3.
  6. minStack.pop();
  7. minStack.top(); --> Returns 0.
  8. minStack.getMin(); --> Returns -2.

Solution:

  1. class MinStack {
  2. Stack<Integer> s1 = new Stack<>();
  3. Stack<Integer[]> s2 = new Stack<>();
  4. public void push(int x) {
  5. s1.push(x);
  6. if (s2.isEmpty() || x < s2.peek()[0]) {
  7. s2.push(new Integer[]{x, 1});
  8. } else if (x == s2.peek()[0]) {
  9. s2.peek()[1]++;
  10. }
  11. }
  12. public void pop() {
  13. if (s1.peek().intValue() == s2.peek()[0]) {
  14. s2.peek()[1]--;
  15. if (s2.peek()[1] == 0)
  16. s2.pop();
  17. }
  18. s1.pop();
  19. }
  20. public int top() {
  21. return s1.peek();
  22. }
  23. public int getMin() {
  24. return s2.peek()[0];
  25. }
  26. }